<template>
  <div>
    <el-dialog v-model="showDialog" :title="title" width="40%" center>
      <el-form :model="userDTO" ref="userDTORef" :label-width="100" label-position="left">
        <el-form-item label="用户名" prop="username" :rules="required">
          <el-input v-model="userDTO.username" placeholder="用户名"></el-input>
        </el-form-item>
        <el-form-item label="手机号" prop="phone" :rules="[required, phone]">
          <el-input v-model="userDTO.phone" placeholder="手机号" />
        </el-form-item>
        <el-form-item label="邮箱" prop="email" :rules="email">
          <el-input v-model="userDTO.email" placeholder="邮箱" />
        </el-form-item>
        <el-form-item label="昵称" prop="nickName" :rules="required">
          <el-input v-model="userDTO.nickName" placeholder="昵称"></el-input>
        </el-form-item>
        <el-form-item label="性别" prop="gender">
          <el-select v-model="userDTO.gender" placeholder="性别">
            <el-option v-for="item in GenderEnum.allEnums()" :key="item.value" :label="item.label" :value="item.value"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="角色" prop="roleList" :rules="required">
          <el-select multiple v-model="userDTO.roleList" placeholder="角色">
            <el-option v-for="item in roleList" :key="item.id" :label="item.roleName" :value="item.id" />
          </el-select>
        </el-form-item>
        <el-form-item label="设置密码" prop="setPassword" :rules="required">
          <div>
            <el-switch :width="65" inline-prompt active-text="设置" inactive-text="不设置" v-model="userDTO.setPassword" />
            <span v-if="!userDTO.setPassword" class="ml-1em txt-0_8em txt-gray-90">默认密码：123456</span>
          </div>
        </el-form-item>
        <div v-if="userDTO.setPassword">
          <el-form-item label="密码" prop="password" :rules="required">
            <el-input type="password" v-model="userDTO.password" placeholder="密码" />
          </el-form-item>
          <el-form-item
              label="确认密码"
              prop="confirmPassword"
              :rules="[required, {trigger: 'change', message: '两次密码输入不一致！', validator: confirmPasswordRule}]">
            <el-input type="password" v-model="userDTO.confirmPassword" placeholder="再次输入密码" />
          </el-form-item>
        </div>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="switchDialog()"> 取 消 </el-button>
          <el-button v-if="isEdit" type="primary" @click="updateById">提 交</el-button>
          <el-button v-else type="primary" @click="add">提 交</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, defineExpose, defineEmits, onMounted, computed } from 'vue'
import { ElMessage } from 'element-plus'
import { required, phone, email } from '@/utils/FormRule'
import GenderEnum from '@/enums/GenderEnum'
import User from '@/api/sys/user'
import Role from '@/api/sys/role'

onMounted(() => {
  Role.list().then(({ result }) => {
    roleList.value = result
  })
})

// 所有角色列表
const roleList = ref([])

// 用户参数
const userDTO = ref({
  id: '',
  setPassword: false,
  username: '',
  password: '',
  confirmPassword: '',
  phone: '',
  email: '',
  nickName: '',
  avatarUrl: '',
  gender: '',
  enabled: false,
  roleList: [],
})

// 自定义密码校验注解, 检查两次输入密码是否一致
const confirmPasswordRule = (rule, value, callback) => {
  if (value !== userDTO.value.password){
    callback(new Error(rule.message))
  }else {
    callback()
  }
}

// 表单Form
const userDTORef = ref()

const emits = defineEmits(['success'])

// 新增一个用户
function add() {
  userDTORef.value.validate(async (valid) => {
    if (valid) {
      await User.create(userDTO.value)
      emits('success')
      switchDialog()
    }
  })
}

// 更新用户信息
function updateById() {
  userDTORef.value.validate(async (valid) => {
    if (valid) {
      await User.update(userDTO.value)
      emits('success')
      switchDialog()
    }
  })
}

// 弹框开关
const showDialog = ref(false)

// 是否编辑，false为新增弹框，true为编辑弹框
const isEdit = ref(false)

// 弹框标题
const title = computed(() => (isEdit.value ? '修改用户' : '新增用户'))

/**
 * 弹框的打开与关闭
 */
function switchDialog(user) {
  // 先判断是新增还是修改
  if (user) {
    isEdit.value = true
    userDTO.value = Object.assign({}, user)
    userDTO.value.setPassword = false
    User.roleList(user.id).then(({ result }) => {
      userDTO.value.roleList = result.map(r => r.id)
    })
  } else {
    // 弹框关闭清空数据
    userDTORef.value !== undefined && userDTORef.value.resetFields()
    userDTO.value.setPassword = false
    userDTO.value.roleList = []
    isEdit.value = false
  }
  showDialog.value = !showDialog.value
}

defineExpose({ switchDialog })
</script>

<style lang="scss" scoped></style>
